import FilePdf from '@/assets/images/file-pdf.svg';
import FileDoc from '@/assets/images/file-doc.svg';
import FileDocx from '@/assets/images/file-docx.svg';
import MarkdownIt from 'markdown-it';
import html2pdf from 'html2pdf.js';
//验证是否是手机号
export function validatePhone(str: string) {
  const reg = /^1[3456789]\d{9}$/;
  return reg.test(str);
}

//验证是否是邮箱
export function validateEmail(str: string) {
  const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  return reg.test(str);
}

/** 获取预设的拓展和图片 */
export const getFileIcon = (extension: string | undefined) => {
  switch (extension) {
    // Document
    case 'pdf':
      return FilePdf;
    case 'doc':
      return FileDoc;
    case 'docx':
      return FileDocx;
  }
  return '';
};
function cleanAndParseJSON(jsonStr: string) {
  const regex = /\{[^{}]*\}/g;
  const res: any = [];
  jsonStr = jsonStr.replace(',,', '},').replace(',],', '}]');
  // console.log(jsonStr.match(regex));
  jsonStr.match(regex)?.forEach((item) => {
    console.log(JSON.parse(item));
    res.push(JSON.parse(item));
  });
  return res;
}
//解析流式传输时候的json
export function parseEventStream(str: string) {
  const tempList = str.replace('event:  Message', '').split('data: ');
  let res: any = {};
  tempList.forEach((item) => {
    let str = item
      .replace('event:  Message', '')
      .replace(/\n/g, '')
      .replace(/\\"/g, '"')
      .slice(2, -1)
      .split('}');
    if (str.length > 1) str = str.slice(0, str.length - 1);
    const temp = str + '}';
    // console.log(
    //   '分割后' + temp + '' + temp.startsWith('{') + '' + temp.endsWith('}')
    // );
    if (temp.startsWith('{') && temp.endsWith('}')) {
      // console.log('转化前' + `"${temp}"`);
      const obj = JSON.parse(`${temp.replace(/\\"/g, '"')}`);
      // console.log(obj);
      res = Object.assign(res, obj);
    }
  });

  if (res['content']) {
    // res['content'] = JSON.parse(res['content']);
    res['content'] = cleanAndParseJSON(res['content'] as string);
  }
  // console.log(res);
  return res;
}

//导出为pdf
export const exportMarkdownToPDF = (
  markdownString: string,
  name: string = 'pdf'
) => {
  const md = new MarkdownIt();
  const htmlContent = md.render(markdownString);
  console.log(htmlContent);
  const container = document.createElement('div');
  container.innerHTML = htmlContent;
  // container.style.all = 'revert';
  // container.style.padding = '10px';
  container.className = 'viewPDF';
  document.querySelector('body')?.appendChild(container);
  console.log(container);
  html2pdf()
    .from(container)
    .save(`${name}.pdf`) // 直接下载 PDF
    .then(() => {
      // document.body.removeChild(container); // 清理 DOM
    });
};
